package cn.tedu.springrabbitmq.m6;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Server {
    public static void main(String[] args) throws IOException, TimeoutException, IOException, TimeoutException {
        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("wht6.cn");  // wht6.cn
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        // 创建调用队列： rpc-queue
        c.queueDeclare("rpc-queue",false,false,false,null);

        // 从 rpc-queue 接收调用信息
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            // 求出斐波那契数
            // 把结果发回到返回队列，携带关联id
            // 从 message 取出： n, 返回队列名, 关联id
            Integer n = Integer.valueOf(new String(message.getBody()));
            String replyTo = message.getProperties().getReplyTo();
            String cid = message.getProperties().getCorrelationId();
            System.out.println("求第"+n+"个斐波那契数");
            long r = fbnq(n);

            AMQP.BasicProperties prop =
                    new AMQP.BasicProperties.Builder()
                            .correlationId(cid)
                            .build();
            c.basicPublish("", replyTo, prop, (r+"").getBytes());
        };
        CancelCallback cancelCallback = consumerTag -> {};
        c.basicConsume("rpc-queue",true,deliverCallback,cancelCallback);


    }

    public static long fbnq(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        /*
                    a  b
        1  1  2  3  5  8

        a = 1
        b = 2

        b = a+b
        a = b-a
         */

        long a = 1;
        long b = 1;
        for (int i = 3; i <= n; i++) {
            b = a+b;
            a = b-a;
        }
        return b;  // 会溢出
    }
}
